import { CACHE_ACCOUNT, CACHE_KEEPPWD, CACHE_PASSWORD, CACHE_USERINFO } from "@/global/constants"
import router from "@/router"
import { accountLogin } from "@/service/login/login"
import type { IAccount } from "@/types"
import { localCache } from "@/utils/cacheData"
import { defineStore } from "pinia"

interface ILoginState {
  userInfo: any
}

const useLoginStore = defineStore("login", {
  state: (): ILoginState => ({
    userInfo: {}
  }),

  actions: {
    async loginAccountAction(account: IAccount, keepPwd: boolean) {
      // 1.账号登录，获取token等信息
      const loginResult = await accountLogin(account)
      // console.log(loginResult)
      if (loginResult.status == 200) {
        this.userInfo = loginResult.data
        localCache.setCache(CACHE_USERINFO, loginResult.data)
        // 1-2.是否保存账号密码
        if (keepPwd) {
          localCache.setCache(CACHE_ACCOUNT, account.userAccount)
          localCache.setCache(CACHE_PASSWORD, account.userPwd)
        } else {
          // 没有勾选记住密码就清空缓存
          localCache.removeCache(CACHE_ACCOUNT)
          localCache.removeCache(CACHE_PASSWORD)
        }
        localCache.setCache(CACHE_KEEPPWD, keepPwd)

        // 5.路由跳转 （main页面中）
        router.push("/main")
      }
    },
    // 用户进行刷新的时候默认加载数据的操作
    loadLocalCacheAction() {
      console.log(" ----用户进行刷新的时候默认加载数据的操作")
    }
  }
})

export default useLoginStore
